package com.ftd.messagelistener.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.ftd.messagelistener.R;
import com.ftd.messagelistener.activity.AlarmConfigActivity;
import com.ftd.messagelistener.base.Constants;
import com.ftd.messagelistener.bean.SMSBean;
import com.ftd.messagelistener.utils.view.CircleWaveView;
import com.ftd.messagelistener.utils.view.ClockView;

import java.lang.ref.WeakReference;

/**
 * 通过Windows窗口模式解决oppo vivio 型号手机无法锁屏唤起的问题
 */
public class LockerHelper {
   // private final Context mContext;
    private WindowManager mWindowManager;// 窗口管理器
    private  WeakReference<View> mLockView;// 锁屏视图
    private WindowManager.LayoutParams wmParams;
    private boolean isLocked;// 是否锁定

    private final WeakReference<Context> mContext;

    private LockListenter lockListenter;//监听 释放资源时用于finishActivity
    private static LockerHelper mInstance;

    private SMSBean smsBean;//接收到的消息体
    //Singleton
    public static LockerHelper getInstance(Context context) {
        if (null == mInstance) {
            mInstance = new LockerHelper(context);
        }
        return mInstance;
    }

    private Ringtone music;


    private final Handler mHandler = new Handler();
    private final Runnable mColockReplay = new Runnable() {

        @Override
        public void run() {
            if (music==null){
                playAlarmMediaPlayer();
            }else if (!music.isPlaying()){
                music.play();
            }

            mHandler.postDelayed(this, 10000);

        }
    };

    /**
     * 构造方法
     */
    public LockerHelper(Context context) {
        this.mContext = new WeakReference<>(context);
        init();
    }
    /**
     * 初始化布局
     */
    private void init() {
        isLocked = false;
        // 获取WindowManager
        mWindowManager = (WindowManager) mContext.get().getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        // 设置LayoutParams(全局变量）相关参数
        wmParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                        | WindowManager.LayoutParams.FLAG_FULLSCREEN,
                PixelFormat.TRANSLUCENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type =  WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;// 关键部分
        }else {
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        wmParams.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        // 设置Window flag
        wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        wmParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        wmParams.flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED //锁屏显示
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕不息屏
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;//状态栏
    }
    public void show(SMSBean smsBean){
        this.smsBean=smsBean;
        mLockView= new  WeakReference<>(LayoutInflater.from(mContext.get()).inflate(R.layout.activity_alarm,null));
        initView();
        initMusic();
        lock();
    }
    public void show(SMSBean smsBean,LockListenter lockListenter){
        this.smsBean=smsBean;
        this.lockListenter=lockListenter;
        mLockView= new  WeakReference<>(LayoutInflater.from(mContext.get()).inflate(R.layout.activity_alarm,null));
        initView();
        initMusic();
        lock();
    }
    public void destory(){
        stopAlarmMediaPlayer();

        if (!SharePrefenceUtil.getValue(mContext.get(),"NOREPEAT_CONFIG_NAOZHONG",false)){
            mHandler.removeCallbacks(mColockReplay);
        }

        music=null;
        unlock();
        if (lockListenter!=null){
            lockListenter.stop();
        }
        mInstance=null;//最后回收自己
    }
    /**
     * 锁屏
     */
    public synchronized void lock() {
        if (mLockView != null && !isLocked) {
            mWindowManager.addView(mLockView.get(), wmParams);
        }
        isLocked = true;
    }
    /**
     * 解锁
     */
    public synchronized void unlock() {
        if (mWindowManager != null && isLocked) {
            mWindowManager.removeView(mLockView.get());
        }
        isLocked = false;
    }


    private void initView(){
        ClockView clockView = mLockView.get().findViewById(R.id.textclock);
        TextView music_control = mLockView.get().findViewById(R.id.music_control);
        AssetManager assets = mContext.get().getAssets();
        Typeface font = Typeface.createFromAsset(assets, Constants.FONT_COLOCK);
        music_control.setTypeface(font);
        clockView.start();
        CircleWaveView circleView=mLockView.get().findViewById(R.id.circle);
        circleView.restart();
        circleView.setRadius(DisplayUtil.dip2px(mContext.get(),150),DisplayUtil.dip2px(mContext.get(),80));
        circleView.setOnClickListener(view -> destory());

        TextView messagefromText=mLockView.get().findViewById(R.id.message_from);
        TextView messagebodyText=mLockView.get().findViewById(R.id.message_body);
        TextView messagedateText=mLockView.get().findViewById(R.id.message_date);
        if (!StringUtils.isEmpty(smsBean.getPhone())){
            messagefromText.setText(Html.fromHtml(smsBean.getPhone()));
        }
        if (!StringUtils.isEmpty(smsBean.getMessage())){
            messagebodyText.setText(Html.fromHtml(smsBean.getMessage()));
        }
        messagedateText.setText(smsBean.getDate());
    }

    private void  initMusic(){
        if (music==null){
            if (!SharePrefenceUtil.getValue(mContext.get(),"NOREPEAT_CONFIG_NAOZHONG",false)){
                mHandler.post(mColockReplay);
            }

            playAlarmMediaPlayer();
        }

    }
    /**
     * 播放系统默认闹钟铃声
     */
    public void playAlarmMediaPlayer() {
        if (music==null){
            if (SharePrefenceUtil.getValue(mContext.get(),"MUSIC_CONFIG_NAOZHONG",false)){
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                music = RingtoneManager.getRingtone(mContext.get(), notification);
            }else {
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                music = RingtoneManager.getRingtone(mContext.get(), notification);
            }//RingtoneManager.TYPE_RINGTONE 来电铃声  RingtoneManager.TYPE_ALARM  闹钟铃声
        }
        music.play();
    }

    /**
     * 播放系统默认闹钟铃声
     */
    public void stopAlarmMediaPlayer() {
        if (music==null){
            if (SharePrefenceUtil.getValue(mContext.get(),"MUSIC_CONFIG_NAOZHONG",false)){
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                music = RingtoneManager.getRingtone(mContext.get(), notification);
            }else {
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                music = RingtoneManager.getRingtone(mContext.get(), notification);
            }//RingtoneManager.TYPE_RINGTONE 来电铃声  RingtoneManager.TYPE_ALARM  闹钟铃声
        }
        music.stop();
    }

    public interface LockListenter{
        void stop();
    }
}
